﻿using System;
using System.Runtime.CompilerServices;
using UnityEngine;

public static class CameraExtension
{
    public static Vector2 GetSize(this Camera cam)
    {
        return new Vector2((cam.orthographicSize * cam.aspect) * 2f, cam.orthographicSize * 2f);
    }

    public static Vector3 GetWorldPositionOnPlane(this Camera camera, Vector3 screenPosition, float z)
    {
        float num;
        Ray ray = camera.ScreenPointToRay(screenPosition);
        new Plane(Vector3.forward, new Vector3(0f, 0f, z)).Raycast(ray, out num);
        return ray.GetPoint(num);
    }

    public static Vector3 GetWorldPositionOnPlaneXZ(this Camera camera, Vector3 screenPosition, float y)
    {
        float num;
        Ray ray = camera.ScreenPointToRay(screenPosition);
        new Plane(Vector3.up, new Vector3(0f, y, 0f)).Raycast(ray, out num);
        return ray.GetPoint(num);
    }

    public static Rect GetWorldRect(this Camera cam)
    {
        return cam.GetWorldRect(cam.transform);
    }

    public static Rect GetWorldRect(this Camera cam, Transform camTsm)
    {
        Vector3 position = camTsm.position;
        Vector2 size = cam.GetSize();
        return new Rect(position.x - (size.x / 2f), position.y - (size.y / 2f), size.x, size.y);
    }

    public static void RenderTo(this Camera cam, RenderTexture rt)
    {
        if (cam != null)
        {
            RenderTexture targetTexture = cam.targetTexture;
            RenderTexture.active = rt;
            cam.targetTexture = rt;
            cam.Render();
            cam.targetTexture = targetTexture;
        }
    }

    public static void SetWorldRect(this Camera cam, Rect rect)
    {
        cam.SetWorldRect(rect, cam.transform);
    }

    public static void SetWorldRect(this Camera cam, Rect rect, Transform camTsm)
    {
        Vector3 position = camTsm.position;
        position.x = rect.center.x;
        position.y = rect.center.y;
        camTsm.position = position;
        float num = rect.width / rect.height;
        if (cam.aspect <= num)
        {
            cam.orthographicSize = rect.height / 2f;
        }
        else
        {
            cam.orthographicSize = (rect.width / cam.aspect) / 2f;
        }
    }
}

